package com.global.college.ui.activity;


import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.gyf.barlibrary.ImmersionBar;
import com.global.college.R;
import com.global.college.api.AuthRequestClient;
import com.global.college.api.ProgressSubscriber;
import com.global.college.base.BaseActivity;
import com.global.college.constants.Constant;
import com.global.college.ui.bean.InviteInfoModel;
import com.global.college.utils.CommonUtils;
import com.global.college.utils.ImageSaveUtil;
import com.global.college.utils.StringUtils;
import com.global.college.utils.TimeUtils;
import com.global.college.utils.ToastUtils;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.ByteArrayOutputStream;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 首页
 */
public class InviteActivity extends BaseActivity {
    @BindView(R.id.iv_invite_bg)
    ImageView ivInviteBg;
    private String inviteCode;

    private Bitmap mBitmap;
    private IWXAPI api;

    @Override
    public int getContentViewId() {
        return R.layout.activity_invite;
    }

    @Override
    public void onCreateNew(Bundle savedInstanceState) {
        //初始化Oss用于上传
        setShowTitleBar(false);

        ImmersionBar.with(this)
                .statusBarDarkFont(true)
                .init();
    }

    @Override
    public void getInitData() {
        api = WXAPIFactory.createWXAPI(this, Constant.WECHAT_PAY_APP_ID,true);
        // 将该app注册到微信
        api.registerApp(Constant.WECHAT_PAY_APP_ID);
        AuthRequestClient.getInstance().getInviteInfo().subscribe(new ProgressSubscriber<InviteInfoModel>(this, true) {
            @Override
            public void onNext(InviteInfoModel model) {
                Glide.with(InviteActivity.this).load(model.getInvitationPath()).into(ivInviteBg);
                inviteCode = model.getInvitationCode();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }
        });
    }



    @OnClick({R.id.iv_back,R.id.tv_invite_history,R.id.tv_invite_wx,R.id.tv_invite_circle,R.id.tv_invite_save,R.id.tv_invite_copy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_invite_history:
                JugeAndOpenActivity(InviteHistoryActivity.class);
                break;
            case R.id.tv_invite_wx:
                if (CommonUtils.isFastClick()) {
                    mBitmap = CommonUtils.view2Bitmap(ivInviteBg);
                    shareLive("wechat",mBitmap);
                }
                break;
            case R.id.tv_invite_circle:
                if (CommonUtils.isFastClick()) {
                    mBitmap = CommonUtils.view2Bitmap(ivInviteBg);
                    shareLive("circle",mBitmap);
                }
                break;
            case R.id.tv_invite_save:
                if (CommonUtils.isFastClick()) {
                    mBitmap = CommonUtils.view2Bitmap(ivInviteBg);
                    String strBitmapName = TimeUtils.getNowTime().trim().replace(":", "").replace("-", "").replace(" ", "");
                    ImageSaveUtil.saveAlbum(this,mBitmap,Bitmap.CompressFormat.JPEG, 100, true);
                    ToastUtils.showToastShort("已保存至相册");
                }
                break;
            case R.id.tv_invite_copy:
                copyContentToClipboard(inviteCode,this);
                ToastUtils.showToastShort("已复制到剪切板");
                break;
            default:
                break;
        }
    }

    private void shareLive(String shareType, Bitmap bmp) {
        if (!api.isWXAppInstalled()) {
            ToastUtils.showToastShort(R.string.you_has_not_install_wechat);
            return;
        }
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                //初始化 WXImageObject 和 WXMediaMessage 对象
                WXImageObject imgObj = new WXImageObject(bmp);
                WXMediaMessage msg = new WXMediaMessage();
                msg.mediaObject = imgObj;
                Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 150, 150, true);
                bmp.recycle();
                msg.thumbData = bmpToByteArray(thumbBmp, true);
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("img");
                if (StringUtils.equals("circle", shareType)) {
                    req.scene = SendMessageToWX.Req.WXSceneTimeline;    //设置发送到朋友圈
                } else {
                    req.scene = SendMessageToWX.Req.WXSceneSession;   //设置发送给朋友
                }
                //req.userOpenId = open_id;
                req.message = msg;
                api.sendReq(req);
            }
        });
        thread.start();
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    /**
     * 复制内容到剪贴板
     *
     * @param content
     * @param context
     */
    public void copyContentToClipboard(String content, Context context) {
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", content);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
    }

}